<template>
  <div class="app-container">
    <div v-if="showSearch" class="search-container">
      <CommonSearch
        :formConfig="searchColumns"
        :inline="true"
        labelWidth="63px"
        formItemWidth="auto"
        :labelPosition="'left'"
        :model="searchParam"
      >
        <template #after>
          <el-button type="primary" @click="berforeSearch">
            <i-ep-search />
            搜索
          </el-button>
          <el-button @click="reset">
            <i-ep-refresh />
            重置
          </el-button>
        </template>
      </CommonSearch>
    </div>

    <el-card shadow="never" class="table-container">
      <template #header>
        <el-button
          @click="
            useDownload('/mdm/mdmmaterial/export', '停机时长统计', searchParam)
          "
        >
          <template #icon><i-ep-download /></template>导出</el-button
        >
      </template>
      <!-- 表格主体 -->
      <el-table
        ref="dataTableRef"
        v-loading="loading"
        v-bind="$attrs"
        :data="tableData"
        highlight-current-row
        border
        @selection-change="handleSelectionChange"
        @sort-change="onTableSortChanged"
      >
        <!-- <el-table-column type="selection" width="55" align="center" /> -->

        <!-- 表格内容操作 -->
        <template v-for="item in tableColumns" :key="item">
          <TableColumn v-if="item.prop && item.isShow" :column="item">
            <template v-for="slot in Object.keys($slots)" #[slot]="scope">
              <slot :name="slot" v-bind="scope"></slot>
            </template>
          </TableColumn>
        </template>
      </el-table>

      <el-pagination
        :background="true"
        :current-page="pageable.pageNum"
        :page-size="pageable.pageSize"
        :page-sizes="[10, 25, 50, 100]"
        :total="pageable.total"
        layout="total, sizes, prev, pager, next, jumper"
        class="mt-[20px]"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <!-- 列设置 抽屉组件 -->
    <!-- <ColSetting
      v-model:col-setting="tableColumns"
      v-model:search-setting="searchColumns"
      @search-handle="(e:boolean) => (showSearch = e)"
    /> -->
  </div>
</template>

<script setup lang="tsx">
import dayjs from "dayjs";
import { useTable, useDictionary, useDownload } from "@/utils/useTable";
import { getYearArray, getMonthsBetween } from "@/utils/commonHooks";
import {
  getworkCenter,
  getMesprocessList,
  getAndstoptypeList,
} from "@/api/andon/andon";

defineOptions({
  name: "ANDONANDSTOPTIMESTATISTICAL",
  inheritAttrs: false,
});

const firstDay = dayjs()
  .year(dayjs().year())
  .startOf("year")
  .format("YYYY-MM-DD");
const nowDay = dayjs().format("YYYY-MM-DD");

// 请求参数
const requestApi = "/andon/andcall/selectShutdownByPage";

// 是否需要分页
const pagination = true;

const initParam = reactive({ sort: {} });

// 初始化搜索参数数据
const searchParamInit = {
  workCenterId: "",
  stopId: "",
  callTimeSearch: [firstDay, nowDay],
  callTimeStart: firstDay,
  callTimeEnd: nowDay,
};

// 数据请求错误后处理
function requestError() {
  // yearList.value = getYearArray(
  //   searchParam.value.callTimeStart,
  //   searchParam.value.callTimeEnd
  // );
  // monthList.value = getMonthsBetween(
  //   searchParam.value.callTimeStart,
  //   searchParam.value.callTimeEnd
  // );
  // tableColumns = Object.assign(
  //   tableColumns,
  //   getTableColumns(yearList.value, monthList.value)
  // );
  // // 当筛选时间范围为2023年6月到2024年2月
  // tableData.value = [
  //   {
  //     id: "12232312",
  //     plantCode: "1212",
  //     workCenterCode: "121vvx2",
  //     workCenterName: "121vxxxxxxx2",
  //     equipmentName: "电机屏",
  //     monthTimesCounts: [
  //       [12, 23, null, 45, 0, 12, 0], // 2023年 [6月，7月...，12月]
  //       [56, 78], // 2024年 [1月，2月]
  //     ],
  //     monthTimes: [
  //       [1002, 203, 56, 415, 100, 102, 0],
  //       [0, 78],
  //     ],
  //   },
  // ];
}

// 数据请求错误后处理
// function dataCallBack(data: any) {
//   return data;
// } //需要处理
const dataCallBack = ref(undefined); //无需二次数据处理&不传赞数也行

// 表格操作 Hooks
const {
  tableData,
  pageable,
  searchParam,
  ids,
  getTableList,
  search,
  reset,
  handleSizeChange,
  handleCurrentChange,
  handleSelectionChange,
  handleTableDelete,
  loading,
}: any = useTable(
  requestApi,
  initParam,
  searchParamInit,
  pagination,
  dataCallBack.value,
  requestError
);

// 监听表格排序方法
const onTableSortChanged = (column: any) => {};

// 年份跨度 [2024, 2025]
const yearList: any = ref(getYearArray(firstDay, nowDay));
// 月份跨度 [[10, 11, 12], [01, 02]]
const monthList: any = ref(getMonthsBetween(firstDay, nowDay));

function getTableColumns(years, months) {
  console.log("getTableColumns", years, months);
  return [
    {
      prop: "plantCode",
      label: "工厂/工作中心/设备",
      isShow: true,
      minWidth: 350,
      render: (scope: any) => (
        <span>
          {`${scope.row?.plantCode ?? ""}/${scope.row.workCenterCode ?? ""}-${
            scope.row.workCenterName ?? ""
          }/${scope.row?.equipmentName ?? ""}`}
        </span>
      ),
    },
    ...years?.map((yearItem, yearIndex) => ({
      prop: `year_${yearItem}`,
      label: `${yearItem}年`,
      minWidth: 100,
      align: "center",
      isShow: true,
      _children: [
        ...months[yearIndex]?.map((monthItem, monthIndex) => ({
          prop: `year_${yearItem}_month_${monthItem}`,
          label: `${monthItem}月`,
          minWidth: 100,
          align: "center",
          isShow: true,
          _children: [
            {
              prop: `year_${yearItem}_month_${monthItem}_count`,
              label: "次数",
              minWidth: 90,
              isShow: true,
              headerAlign: "center",
              align: "right",
              render: (scope: any) => (
                <span>
                  {scope?.row?.monthTimesCounts[yearIndex]
                    ? scope?.row?.monthTimesCounts[yearIndex][monthIndex] ?? ""
                    : ""}
                </span>
              ),
            },
            {
              prop: `year_${yearItem}_month_${monthItem}_time`,
              label: "时长",
              minWidth: 90,
              isShow: true,
              headerAlign: "center",
              align: "right",
              render: (scope: any) => (
                <span>
                  {scope?.row?.monthTimesCounts[yearIndex]
                    ? scope?.row?.monthTimes[yearIndex][monthIndex] ?? ""
                    : ""}
                </span>
              ),
            },
          ],
        })),
      ],
    })),
  ];
}
let tableColumns = reactive(getTableColumns(yearList.value, monthList.value));

// 获取工作中心列表
const getWorkCenterList = async () => {
  const { data } = await getworkCenter();
  searchColumns.find((item) => item.fieldName === "workCenterId").optionList =
    data.map((item) => ({
      label: item.workshopCode + "-" + item.workshopName,
      value: item.id,
    }));
};

// 获取停机类型列表
const getStopList = async () => {
  const { data } = await getAndstoptypeList();
  searchColumns.find((item) => item.fieldName === "stopId").optionList =
    data.map((item) => ({
      label: item.stopTypeName,
      value: item.id,
    }));
};

// 是否显示搜索框
const showSearch = ref(true);
// 搜索参数 设置为响应式
const searchColumns: any = reactive([
  {
    type: "select",
    label: "工作中心",
    isShow: true,
    fieldName: "workCenterId",
    placeholder: "请选择工作中心",
    initValue: null,
    defaultFirstOption: true,
    filterable: true,
    optionList: [],
  },
  {
    type: "select",
    label: "停机类型",
    isShow: true,
    fieldName: "stopId",
    placeholder: "请选择停机类型",
    initValue: null,
    defaultFirstOption: true,
    filterable: true,
    optionList: [],
  },
  {
    type: "date",
    dataType: "daterange",
    label: "呼叫时间",
    isShow: true,
    fieldName: "callTimeSearch",
    startPlaceholder: "请选择开始日期",
    endPlaceholder: "请选择结束日期",
    initValue: null,
    valueFormat: "YYYY-MM-DD",
    defaultFirstOption: true,
    change: (val) => {
      if (val) {
        searchParam.value.callTimeStart = val[0];
        searchParam.value.callTimeEnd = val[1];
      } else {
        searchParam.value.callTimeStart = "";
        searchParam.value.callTimeEnd = "";
      }
    },
  },
]);

function berforeSearch() {
  if (!searchParam.value.callTimeStart) {
    ElMessage.error("请选择呼叫时间");
  } else {
    search();
  }
}

watch(
  () => tableData.value,
  (newVal) => {
    console.log("newVal", newVal);
    yearList.value = getYearArray(
      searchParam.value.callTimeStart,
      searchParam.value.callTimeEnd
    );
    monthList.value = getMonthsBetween(
      searchParam.value.callTimeStart,
      searchParam.value.callTimeEnd
    );
    tableColumns = getTableColumns(yearList.value, monthList.value);
    // tableColumns = Object.assign(
    //   tableColumns,
    //   getTableColumns(yearList.value, monthList.value)
    // );
  },
  {
    deep: true,
  }
);

onMounted(async () => {
  await Promise.all([getTableList(), getStopList(), getWorkCenterList()]);
});
</script>

<style scoped lang="scss">
:deep(.el-table--border th.el-table__cell) {
  padding: 5px 0;
}
</style>
